import axios from "axios"
import store from '@/store/'
const request = axios.create({
  baseURL:'http://localhost:8080/'
})

//请求拦截器
// 请求拦截器
// Add a request interceptor
request.interceptors.request.use(function (config) {
  // Do something before request is sent
  const { user } = store.state

  if (config.url=='sys/user/login'){
    return config
  }

    // 如果用户已登录，统一给接口设置 token 信息
    if (user) {
    config.headers.token = `${user.token}`
  }

  // 处理完之后一定要把 config 返回，否则请求就会停在这里
  return config
}, function (error) {
  // Do something with request error
  return Promise.reject(error)
})
//响应拦截器

// 拦截响应response，并做一些错误处理
request.interceptors.response.use(
    response => {
      // 登录失效处理
      if (response.data.code == "401") {
          store.state.user = null
          window.localStorage.clear()
          window.location.href = "/login"
      }
      return response;
    },
    error => {
      return Promise.reject(error);
    }
);

export default request
